package youcaihuaoa.weetop.com.ui.main

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.FragmentUtils
import com.robot.base.base.activity.GLBaseFragment
import com.robot.base.common.api.GlBaseApi
import com.robot.base.configs.AppConstants
import com.robot.base.model.GroupAddBean
import com.robot.base.model.MyFriendBean
import com.robot.base.util.LiveDataBus
import io.rong.imkit.RongIM
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.ConversationIdentifier
import io.rong.imlib.model.Group
import io.rong.imlib.model.UserInfo
import me.goldze.mvvmhabit.BR
import youcaihuaoa.weetop.com.R
import youcaihuaoa.weetop.com.databinding.AppFragmentLifebuoyBinding
import youcaihuaoa.weetop.com.im.GLConversationFragment
import youcaihuaoa.weetop.com.ui.adapter.MessageGroupAdapter
import youcaihuaoa.weetop.com.ui.adapter.MyFriendAdapter
import youcaihuaoa.weetop.com.vm.main.LifebuoyFragmentViewModel


/**
 * 消息
 */
class LifebuoyFragment : GLBaseFragment<AppFragmentLifebuoyBinding, LifebuoyFragmentViewModel>() {
    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int = R.layout.app_fragment_lifebuoy

    private lateinit var conversationFragment: GLConversationFragment
    private lateinit var friendAdapter: MyFriendAdapter
    private lateinit var messageGroupAdapter: MessageGroupAdapter

    override fun initVariableId(): Int = BR.viewModel

    override fun initComponents() {
        conversationFragment = GLConversationFragment()
        FragmentUtils.add(childFragmentManager, conversationFragment, R.id.container)
        friendAdapter = MyFriendAdapter()
        friendAdapter.setOnItemClickListener { adapter, view, position ->
            val friendId = friendAdapter.data[position].friend_id
            RouteUtils.routeToConversationActivity(
                this.context,
                ConversationIdentifier.obtainPrivate(friendId)
            )
        }

        viewModel.initData()
        RongIM.setUserInfoProvider({ it ->
            var myFriendBean: MyFriendBean? = null
            viewModel.myFriendBeanList.forEach { it1 ->
                if (it1.friend_id == it) {
                    myFriendBean = it1
                }
            }
            UserInfo(
                it, myFriendBean?.friend_name, if (myFriendBean != null) {
                    Uri.parse(GlBaseApi.PIC_BASE_URL + myFriendBean?.friend_head_img)
                } else {
                    null
                }
            )
        }, true);//获取用户信息
        RongIM.setGroupInfoProvider({ it ->
            var group: GroupAddBean? = null
            viewModel.groupAddBeanList.forEach { it1 ->
                if (it1.id == it) {
                    group = it1
                }
            }
            Group(it, group?.title, null)
        }, true);

        messageGroupAdapter = MessageGroupAdapter(viewModel.groupTabType.get() ?: 1).apply {
            setOnItemClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.item_tv_add -> {
                        if (viewModel.groupTabType.get() == 1) {
                            viewModel.ryimGroupDel(messageGroupAdapter.data[position].id ?: "")
                        } else {
                            viewModel.ryimGroupUserOut(messageGroupAdapter.data[position].id ?: "")
                        }
                    }
                    else -> {
                        val group = messageGroupAdapter.data[position]
                        val conversationType = Conversation.ConversationType.GROUP;
                        val targetId = group.id;
                        val title = group.title;

                        val conversationIdentifier =
                            ConversationIdentifier(Conversation.ConversationType.GROUP, targetId)
                        RouteUtils.routeToConversationActivity(
                            this.context,
                            conversationIdentifier,
                            Bundle().apply {
                                putString(RouteUtils.TITLE, title)
                            }
                        )
//                        RongIM.getInstance()
//                            .startConversation(context, conversationType, targetId, title, 0)
                    }
                }
            }
        }

        binding.friendList.apply {
            layoutManager = LinearLayoutManager(context)
        }
    }

    override fun initViewObservable() {
        viewModel.uiEvent.menuDataLiveEvent.observe(this) {
            if (viewModel.tabType.get() == 2) {
                binding.friendList.adapter = friendAdapter

                binding.friendList.visibility = View.VISIBLE
                FragmentUtils.hide(conversationFragment)
            }
            friendAdapter.setNewInstance(it as MutableList<MyFriendBean>?)
//            it.forEach {
//                RongIM.getInstance().refreshUserInfoCache(
//                    UserInfo(
//                        it.friend_id ?: "",
//                        it.friend_name,
//                        Uri.parse(it.friend_head_img)
//                    )
//                )
//            }
        }
        viewModel.uiEvent.showTab1Event.observe(this) {
            if (viewModel.tabType.get() == 1) {
                binding.friendList.visibility = View.GONE
                FragmentUtils.show(conversationFragment)
            }
        }
        viewModel.uiEvent.groupDataEvent.observe(this) {
            if (viewModel.tabType.get() == 3) {
                binding.friendList.adapter = messageGroupAdapter

                binding.friendList.visibility = View.VISIBLE
                FragmentUtils.hide(conversationFragment)
            }
//            it.forEach {
//                RongIM.getInstance().refreshGroupInfoCache(Group(it.id ?: "", it.title, null))
//            }
            messageGroupAdapter.type = viewModel.groupTabType.get() ?: 1
            messageGroupAdapter.setList(it)
        }

        LiveDataBus.get().with(AppConstants.LiveKey.REFRESH_ADD_GROUP).observe(this) {
            viewModel.ryimGroupList("${viewModel.groupTabType.get() ?: 1}")
        }
    }

}